<?php

//index controller

class indexController extends Action{

	private $setup;
	
	public function __Construct() {
		parent::__Construct();
		$this->getMsgSetup();

	}
	
	function index(){
		$num = $this->setup['msg_num'];
		//$num 分页条数
		$data = $this->toPage('msgs', 'p','page', $num);
		$this->Template();
		$this->assign('toPage',$data);
		$this->assign('title','首页');
		$_SESSION['formkey'] = md5(time().'naryn');
		$this->assign('formkey',$_SESSION['formkey']);
		$this->display('index');
	}
	
	
	function add(){
		
		$error = '';
		if (isset($_POST['submitadd'])){

			$setup =  $this->setup;
		
			if (!$setup['msg_activate']){
				$this->error('Message system closed !');
			}
		
			if($_SESSION['formkey'] != $_POST['formkey']){
				$this->error('Invalid form !');
			}
			
			if ($_SESSION['VCODE']!=md5($_POST['yzm'])){
				$this->error('VCODE error !','');
			}
			$content = stripslashes($_POST['content']);
			$content = $this->chkLength($content);
			
			if(!$this->badWord($content)){
				$this->error('Contain bad word !');
			}
			
			$content = $this->htmlCode2Str($content);
			
			$data['msg_time'] = date('Y-m-d H:i:s',time());
			$data['msg_content'] = $content;
			
			$obj = $this->M('msgs');
			if($obj->insert($data)){
				$this->success('Message success !');
				
			}else{
				$this->error('Message fail !');
			}
			
		}
		
	}
	
	
	private function badWord($content){
		$bwa = array();
		$badword = $this->setup['msg_badword'];
		$bwa = explode(',', $badword);

		foreach ($bwa as $search )
		{
			if(stristr($content,$search))
				return false;
		}
		return true;
	}
	
	private function htmlCode2Str($content){
		
		return htmlspecialchars($content,ENT_QUOTES);
	}
	
	private function chkLength($content){
		if(mb_strlen($content)<= mb_strlen('你也想留言？那动起鼠标键盘吧！')){
			$this->error('Message is too short !');
		}
		$strlen = $this->setup['msg_length'];
		return mb_substr($content, 0,$strlen,utf8);
	}
	
	private function getMsgSetup(){
		//read file setup
		//or read mysql data table ;
		$objsetup = $this->M('msgsetup');
		$result = $objsetup->limit('','','limit 1');
		$this->setup = $result[0];
		return $result[0];

	}
	

}



?>